import { Route, Routes, useLocation, useNavigate } from 'react-router-dom';
import { injectLogin, useLogin } from '@/pages/login';

import routes from './routes.config';
import { Component, useEffect } from 'react';

const PageRoutes = () => {
    const { pathname } = useLocation();
    const navigate = useNavigate();
    const { isLogin } = useLogin();

    useEffect(() => {
        if (pathname !== '/login' && !isLogin) {
            navigate('/login');
        }

        if (pathname === '/login' && isLogin) {
            navigate('/');
        }
    }, [pathname, isLogin])

    return (
        <Routes>
            {
                routes.map(({ path, element }) => (
                    <Route key={path} path={path} element={element}></Route>
                ))
            }
        </Routes>
    )
}

@injectLogin
class PageRoutesWrapper extends Component {
    render() {
        return (
            <PageRoutes />
        )
    }
}

export default PageRoutesWrapper;